package com.vincent.jvmtest.Jdbc;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SQLValid {

    static String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
            + "(\\b(select|update|and|or|delete|insert|truncate|char|into|substr|ascii|declare|exec|count|master|drop|execute)\\b)";

    static Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);//表示忽略大小写

    static String reg2 = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
            + "(\\b(select|update|delete|insert|truncate|declare|exec|drop|execute)\\b)";

    static Pattern sqlPattern2= Pattern.compile(reg2, Pattern.CASE_INSENSITIVE);//表示忽略大小写
    /***************************************************************************
     * 参数校验
     *
     * @param str ep: "or 1=1"
     */
    public static boolean isSqlValid(String str) {
        Matcher matcher = sqlPattern.matcher(str);
        if (matcher.find()) {
            System.out.println("参数存在非法字符，请确认："+matcher.group());//获取非法字符：or
            return false;
        }
        return true;
    }

    public static boolean isSqlWhereValid(String str) {
        Matcher matcher = sqlPattern2.matcher(str);
        if (matcher.find()) {
            System.out.println("参数存在非法字符，请确认："+matcher.group());//获取非法字符：or
            return false;
        }
        System.out.println("sql校验通过");
        return true;
    }

    public static void main(String[] args) {
        isSqlValid("or 1=1");
        isSqlValid("sfz = (select 1 from tb1)");
        isSqlWhereValid("sfzselect");
        isSqlWhereValid("or 1=1");
    }
}
